Support multi-content diffs on Special:Undelete
[lhc/web/wiklou.git] / includes / specials / SpecialUndelete.php
1 <?php
2 /**
3 * Implements Special:Undelete
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Storage\RevisionRecord;
26 use Wikimedia\Rdbms\IResultWrapper;
27
28 /**
29 * Special page allowing users with the appropriate permissions to view
30 * and restore deleted content.
31 *
32 * @ingroup SpecialPage
33 */
34 class SpecialUndelete extends SpecialPage {
35 private $mAction;
36 private $mTarget;
37 private $mTimestamp;
38 private $mRestore;
39 private $mRevdel;
40 private $mInvert;
41 private $mFilename;
42 private $mTargetTimestamp;
43 private $mAllowed;
44 private $mCanView;
45 private $mComment;
46 private $mToken;
47
48 /** @var Title */
49 private $mTargetObj;
50 /**
51 * @var string Search prefix
52 */
53 private $mSearchPrefix;
54
55 function __construct() {
56 parent::__construct( 'Undelete', 'deletedhistory' );
57 }
58
59 public function doesWrites() {
60 return true;
61 }
62
63 function loadRequest( $par ) {
64 $request = $this->getRequest();
65 $user = $this->getUser();
66
67 $this->mAction = $request->getVal( 'action' );
68 if ( $par !== null && $par !== '' ) {
69 $this->mTarget = $par;
70 } else {
71 $this->mTarget = $request->getVal( 'target' );
72 }
73
74 $this->mTargetObj = null;
75
76 if ( $this->mTarget !== null && $this->mTarget !== '' ) {
77 $this->mTargetObj = Title::newFromText( $this->mTarget );
78 }
79
80 $this->mSearchPrefix = $request->getText( 'prefix' );
81 $time = $request->getVal( 'timestamp' );
82 $this->mTimestamp = $time ? wfTimestamp( TS_MW, $time ) : '';
83 $this->mFilename = $request->getVal( 'file' );
84
85 $posted = $request->wasPosted() &&
86 $user->matchEditToken( $request->getVal( 'wpEditToken' ) );
87 $this->mRestore = $request->getCheck( 'restore' ) && $posted;
88 $this->mRevdel = $request->getCheck( 'revdel' ) && $posted;
89 $this->mInvert = $request->getCheck( 'invert' ) && $posted;
90 $this->mPreview = $request->getCheck( 'preview' ) && $posted;
91 $this->mDiff = $request->getCheck( 'diff' );
92 $this->mDiffOnly = $request->getBool( 'diffonly', $this->getUser()->getOption( 'diffonly' ) );
93 $this->mComment = $request->getText( 'wpComment' );
94 $this->mUnsuppress = $request->getVal( 'wpUnsuppress' ) && $user->isAllowed( 'suppressrevision' );
95 $this->mToken = $request->getVal( 'token' );
96
97 if ( $this->isAllowed( 'undelete' ) && !$user->isBlocked() ) {
98 $this->mAllowed = true; // user can restore
99 $this->mCanView = true; // user can view content
100 } elseif ( $this->isAllowed( 'deletedtext' ) ) {
101 $this->mAllowed = false; // user cannot restore
102 $this->mCanView = true; // user can view content
103 $this->mRestore = false;
104 } else { // user can only view the list of revisions
105 $this->mAllowed = false;
106 $this->mCanView = false;
107 $this->mTimestamp = '';
108 $this->mRestore = false;
109 }
110
111 if ( $this->mRestore || $this->mInvert ) {
112 $timestamps = [];
113 $this->mFileVersions = [];
114 foreach ( $request->getValues() as $key => $val ) {
115 $matches = [];
116 if ( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
117 array_push( $timestamps, $matches[1] );
118 }
119
120 if ( preg_match( '/^fileid(\d+)$/', $key, $matches ) ) {
121 $this->mFileVersions[] = intval( $matches[1] );
122 }
123 }
124 rsort( $timestamps );
125 $this->mTargetTimestamp = $timestamps;
126 }
127 }
128
129 /**
130 * Checks whether a user is allowed the permission for the
131 * specific title if one is set.
132 *
133 * @param string $permission
134 * @param User|null $user
135 * @return bool
136 */
137 protected function isAllowed( $permission, User $user = null ) {
138 $user = $user ?: $this->getUser();
139 if ( $this->mTargetObj !== null ) {
140 return $this->mTargetObj->userCan( $permission, $user );
141 } else {
142 return $user->isAllowed( $permission );
143 }
144 }
145
146 function userCanExecute( User $user ) {
147 return $this->isAllowed( $this->mRestriction, $user );
148 }
149
150 function execute( $par ) {
151 $this->useTransactionalTimeLimit();
152
153 $user = $this->getUser();
154
155 $this->setHeaders();
156 $this->outputHeader();
157
158 $this->loadRequest( $par );
159 $this->checkPermissions(); // Needs to be after mTargetObj is set
160
161 $out = $this->getOutput();
162
163 if ( is_null( $this->mTargetObj ) ) {
164 $out->addWikiMsg( 'undelete-header' );
165
166 # Not all users can just browse every deleted page from the list
167 if ( $user->isAllowed( 'browsearchive' ) ) {
168 $this->showSearchForm();
169 }
170
171 return;
172 }
173
174 $this->addHelpLink( 'Help:Undelete' );
175 if ( $this->mAllowed ) {
176 $out->setPageTitle( $this->msg( 'undeletepage' ) );
177 } else {
178 $out->setPageTitle( $this->msg( 'viewdeletedpage' ) );
179 }
180
181 $this->getSkin()->setRelevantTitle( $this->mTargetObj );
182
183 if ( $this->mTimestamp !== '' ) {
184 $this->showRevision( $this->mTimestamp );
185 } elseif ( $this->mFilename !== null && $this->mTargetObj->inNamespace( NS_FILE ) ) {
186 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFilename );
187 // Check if user is allowed to see this file
188 if ( !$file->exists() ) {
189 $out->addWikiMsg( 'filedelete-nofile', $this->mFilename );
190 } elseif ( !$file->userCan( File::DELETED_FILE, $user ) ) {
191 if ( $file->isDeleted( File::DELETED_RESTRICTED ) ) {
192 throw new PermissionsError( 'suppressrevision' );
193 } else {
194 throw new PermissionsError( 'deletedtext' );
195 }
196 } elseif ( !$user->matchEditToken( $this->mToken, $this->mFilename ) ) {
197 $this->showFileConfirmationForm( $this->mFilename );
198 } else {
199 $this->showFile( $this->mFilename );
200 }
201 } elseif ( $this->mAction === "submit" ) {
202 if ( $this->mRestore ) {
203 $this->undelete();
204 } elseif ( $this->mRevdel ) {
205 $this->redirectToRevDel();
206 }
207
208 } else {
209 $this->showHistory();
210 }
211 }
212
213 /**
214 * Convert submitted form data to format expected by RevisionDelete and
215 * redirect the request
216 */
217 private function redirectToRevDel() {
218 $archive = new PageArchive( $this->mTargetObj );
219
220 $revisions = [];
221
222 foreach ( $this->getRequest()->getValues() as $key => $val ) {
223 $matches = [];
224 if ( preg_match( "/^ts(\d{14})$/", $key, $matches ) ) {
225 $revisions[ $archive->getRevision( $matches[1] )->getId() ] = 1;
226 }
227 }
228 $query = [
229 "type" => "revision",
230 "ids" => $revisions,
231 "target" => $this->mTargetObj->getPrefixedText()
232 ];
233 $url = SpecialPage::getTitleFor( 'Revisiondelete' )->getFullURL( $query );
234 $this->getOutput()->redirect( $url );
235 }
236
237 function showSearchForm() {
238 $out = $this->getOutput();
239 $out->setPageTitle( $this->msg( 'undelete-search-title' ) );
240 $fuzzySearch = $this->getRequest()->getVal( 'fuzzy', true );
241
242 $out->enableOOUI();
243
244 $fields[] = new OOUI\ActionFieldLayout(
245 new OOUI\TextInputWidget( [
246 'name' => 'prefix',
247 'inputId' => 'prefix',
248 'infusable' => true,
249 'value' => $this->mSearchPrefix,
250 'autofocus' => true,
251 ] ),
252 new OOUI\ButtonInputWidget( [
253 'label' => $this->msg( 'undelete-search-submit' )->text(),
254 'flags' => [ 'primary', 'progressive' ],
255 'inputId' => 'searchUndelete',
256 'type' => 'submit',
257 ] ),
258 [
259 'label' => new OOUI\HtmlSnippet(
260 $this->msg(
261 $fuzzySearch ? 'undelete-search-full' : 'undelete-search-prefix'
262 )->parse()
263 ),
264 'align' => 'left',
265 ]
266 );
267
268 $fieldset = new OOUI\FieldsetLayout( [
269 'label' => $this->msg( 'undelete-search-box' )->text(),
270 'items' => $fields,
271 ] );
272
273 $form = new OOUI\FormLayout( [
274 'method' => 'get',
275 'action' => wfScript(),
276 ] );
277
278 $form->appendContent(
279 $fieldset,
280 new OOUI\HtmlSnippet(
281 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
282 Html::hidden( 'fuzzy', $fuzzySearch )
283 )
284 );
285
286 $out->addHTML(
287 new OOUI\PanelLayout( [
288 'expanded' => false,
289 'padded' => true,
290 'framed' => true,
291 'content' => $form,
292 ] )
293 );
294
295 # List undeletable articles
296 if ( $this->mSearchPrefix ) {
297 // For now, we enable search engine match only when specifically asked to
298 // by using fuzzy=1 parameter.
299 if ( $fuzzySearch ) {
300 $result = PageArchive::listPagesBySearch( $this->mSearchPrefix );
301 } else {
302 $result = PageArchive::listPagesByPrefix( $this->mSearchPrefix );
303 }
304 $this->showList( $result );
305 }
306 }
307
308 /**
309 * Generic list of deleted pages
310 *
311 * @param IResultWrapper $result
312 * @return bool
313 */
314 private function showList( $result ) {
315 $out = $this->getOutput();
316
317 if ( $result->numRows() == 0 ) {
318 $out->addWikiMsg( 'undelete-no-results' );
319
320 return false;
321 }
322
323 $out->addWikiMsg( 'undeletepagetext', $this->getLanguage()->formatNum( $result->numRows() ) );
324
325 $linkRenderer = $this->getLinkRenderer();
326 $undelete = $this->getPageTitle();
327 $out->addHTML( "<ul id='undeleteResultsList'>\n" );
328 foreach ( $result as $row ) {
329 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
330 if ( $title !== null ) {
331 $item = $linkRenderer->makeKnownLink(
332 $undelete,
333 $title->getPrefixedText(),
334 [],
335 [ 'target' => $title->getPrefixedText() ]
336 );
337 } else {
338 // The title is no longer valid, show as text
339 $item = Html::element(
340 'span',
341 [ 'class' => 'mw-invalidtitle' ],
342 Linker::getInvalidTitleDescription(
343 $this->getContext(),
344 $row->ar_namespace,
345 $row->ar_title
346 )
347 );
348 }
349 $revs = $this->msg( 'undeleterevisions' )->numParams( $row->count )->parse();
350 $out->addHTML( "<li class='undeleteResult'>{$item} ({$revs})</li>\n" );
351 }
352 $result->free();
353 $out->addHTML( "</ul>\n" );
354
355 return true;
356 }
357
358 private function showRevision( $timestamp ) {
359 if ( !preg_match( '/[0-9]{14}/', $timestamp ) ) {
360 return;
361 }
362
363 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
364 if ( !Hooks::run( 'UndeleteForm::showRevision', [ &$archive, $this->mTargetObj ] ) ) {
365 return;
366 }
367 $rev = $archive->getRevision( $timestamp );
368
369 $out = $this->getOutput();
370 $user = $this->getUser();
371
372 if ( !$rev ) {
373 $out->addWikiMsg( 'undeleterevision-missing' );
374
375 return;
376 }
377
378 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
379 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
380 $out->wrapWikiMsg(
381 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
382 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
383 'rev-suppressed-text-permission' : 'rev-deleted-text-permission'
384 );
385
386 return;
387 }
388
389 $out->wrapWikiMsg(
390 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
391 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
392 'rev-suppressed-text-view' : 'rev-deleted-text-view'
393 );
394 $out->addHTML( '<br />' );
395 // and we are allowed to see...
396 }
397
398 if ( $this->mDiff ) {
399 $previousRev = $archive->getPreviousRevision( $timestamp );
400 if ( $previousRev ) {
401 $this->showDiff( $previousRev, $rev );
402 if ( $this->mDiffOnly ) {
403 return;
404 }
405
406 $out->addHTML( '<hr />' );
407 } else {
408 $out->addWikiMsg( 'undelete-nodiff' );
409 }
410 }
411
412 $link = $this->getLinkRenderer()->makeKnownLink(
413 $this->getPageTitle( $this->mTargetObj->getPrefixedDBkey() ),
414 $this->mTargetObj->getPrefixedText()
415 );
416
417 $lang = $this->getLanguage();
418
419 // date and time are separate parameters to facilitate localisation.
420 // $time is kept for backward compat reasons.
421 $time = $lang->userTimeAndDate( $timestamp, $user );
422 $d = $lang->userDate( $timestamp, $user );
423 $t = $lang->userTime( $timestamp, $user );
424 $userLink = Linker::revUserTools( $rev );
425
426 $content = $rev->getContent( RevisionRecord::FOR_THIS_USER, $user );
427
428 // TODO: MCR: this will have to become something like $hasTextSlots and $hasNonTextSlots
429 $isText = ( $content instanceof TextContent );
430
431 if ( $this->mPreview || $isText ) {
432 $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
433 } else {
434 $openDiv = '<div id="mw-undelete-revision">';
435 }
436 $out->addHTML( $openDiv );
437
438 // Revision delete links
439 if ( !$this->mDiff ) {
440 $revdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
441 if ( $revdel ) {
442 $out->addHTML( "$revdel " );
443 }
444 }
445
446 $out->addHTML( $this->msg( 'undelete-revision' )->rawParams( $link )->params(
447 $time )->rawParams( $userLink )->params( $d, $t )->parse() . '</div>' );
448
449 if ( !Hooks::run( 'UndeleteShowRevision', [ $this->mTargetObj, $rev ] ) ) {
450 return;
451 }
452
453 if ( $this->mPreview || !$isText ) {
454 // NOTE: non-text content has no source view, so always use rendered preview
455
456 $popts = $out->parserOptions();
457 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
458
459 $rendered = $renderer->getRenderedRevision(
460 $rev->getRevisionRecord(),
461 $popts,
462 $user,
463 [ 'audience' => RevisionRecord::FOR_THIS_USER ]
464 );
465
466 // Fail hard if the audience check fails, since we already checked
467 // at the beginning of this method.
468 $pout = $rendered->getRevisionParserOutput();
469
470 $out->addParserOutput( $pout, [
471 'enableSectionEditLinks' => false,
472 ] );
473 }
474
475 $out->enableOOUI();
476 $buttonFields = [];
477
478 if ( $isText ) {
479 // TODO: MCR: make this work for multiple slots
480 // source view for textual content
481 $sourceView = Xml::element( 'textarea', [
482 'readonly' => 'readonly',
483 'cols' => 80,
484 'rows' => 25
485 ], $content->getNativeData() . "\n" );
486
487 $buttonFields[] = new OOUI\ButtonInputWidget( [
488 'type' => 'submit',
489 'name' => 'preview',
490 'label' => $this->msg( 'showpreview' )->text()
491 ] );
492 } else {
493 $sourceView = '';
494 $previewButton = '';
495 }
496
497 $buttonFields[] = new OOUI\ButtonInputWidget( [
498 'name' => 'diff',
499 'type' => 'submit',
500 'label' => $this->msg( 'showdiff' )->text()
501 ] );
502
503 $out->addHTML(
504 $sourceView .
505 Xml::openElement( 'div', [
506 'style' => 'clear: both' ] ) .
507 Xml::openElement( 'form', [
508 'method' => 'post',
509 'action' => $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] ) ] ) .
510 Xml::element( 'input', [
511 'type' => 'hidden',
512 'name' => 'target',
513 'value' => $this->mTargetObj->getPrefixedDBkey() ] ) .
514 Xml::element( 'input', [
515 'type' => 'hidden',
516 'name' => 'timestamp',
517 'value' => $timestamp ] ) .
518 Xml::element( 'input', [
519 'type' => 'hidden',
520 'name' => 'wpEditToken',
521 'value' => $user->getEditToken() ] ) .
522 new OOUI\FieldLayout(
523 new OOUI\Widget( [
524 'content' => new OOUI\HorizontalLayout( [
525 'items' => $buttonFields
526 ] )
527 ] )
528 ) .
529 Xml::closeElement( 'form' ) .
530 Xml::closeElement( 'div' )
531 );
532 }
533
534 /**
535 * Build a diff display between this and the previous either deleted
536 * or non-deleted edit.
537 *
538 * @param Revision $previousRev
539 * @param Revision $currentRev
540 * @return string HTML
541 */
542 function showDiff( $previousRev, $currentRev ) {
543 $diffContext = clone $this->getContext();
544 $diffContext->setTitle( $currentRev->getTitle() );
545 $diffContext->setWikiPage( WikiPage::factory( $currentRev->getTitle() ) );
546
547 $diffEngine = $currentRev->getContentHandler()->createDifferenceEngine( $diffContext );
548 $diffEngine->setRevisions( $previousRev->getRevisionRecord(), $currentRev->getRevisionRecord() );
549 $diffEngine->showDiffStyle();
550 $formattedDiff = $diffEngine->getDiff(
551 $this->diffHeader( $previousRev, 'o' ),
552 $this->diffHeader( $currentRev, 'n' )
553 );
554
555 $this->getOutput()->addHTML( "<div>$formattedDiff</div>\n" );
556 }
557
558 /**
559 * @param Revision $rev
560 * @param string $prefix
561 * @return string
562 */
563 private function diffHeader( $rev, $prefix ) {
564 $isDeleted = !( $rev->getId() && $rev->getTitle() );
565 if ( $isDeleted ) {
566 /// @todo FIXME: $rev->getTitle() is null for deleted revs...?
567 $targetPage = $this->getPageTitle();
568 $targetQuery = [
569 'target' => $this->mTargetObj->getPrefixedText(),
570 'timestamp' => wfTimestamp( TS_MW, $rev->getTimestamp() )
571 ];
572 } else {
573 /// @todo FIXME: getId() may return non-zero for deleted revs...
574 $targetPage = $rev->getTitle();
575 $targetQuery = [ 'oldid' => $rev->getId() ];
576 }
577
578 // Add show/hide deletion links if available
579 $user = $this->getUser();
580 $lang = $this->getLanguage();
581 $rdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
582
583 if ( $rdel ) {
584 $rdel = " $rdel";
585 }
586
587 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
588
589 $tags = wfGetDB( DB_REPLICA )->selectField(
590 'tag_summary',
591 'ts_tags',
592 [ 'ts_rev_id' => $rev->getId() ],
593 __METHOD__
594 );
595 $tagSummary = ChangeTags::formatSummaryRow( $tags, 'deleteddiff', $this->getContext() );
596
597 // FIXME This is reimplementing DifferenceEngine#getRevisionHeader
598 // and partially #showDiffPage, but worse
599 return '<div id="mw-diff-' . $prefix . 'title1"><strong>' .
600 $this->getLinkRenderer()->makeLink(
601 $targetPage,
602 $this->msg(
603 'revisionasof',
604 $lang->userTimeAndDate( $rev->getTimestamp(), $user ),
605 $lang->userDate( $rev->getTimestamp(), $user ),
606 $lang->userTime( $rev->getTimestamp(), $user )
607 )->text(),
608 [],
609 $targetQuery
610 ) .
611 '</strong></div>' .
612 '<div id="mw-diff-' . $prefix . 'title2">' .
613 Linker::revUserTools( $rev ) . '<br />' .
614 '</div>' .
615 '<div id="mw-diff-' . $prefix . 'title3">' .
616 $minor . Linker::revComment( $rev ) . $rdel . '<br />' .
617 '</div>' .
618 '<div id="mw-diff-' . $prefix . 'title5">' .
619 $tagSummary[0] . '<br />' .
620 '</div>';
621 }
622
623 /**
624 * Show a form confirming whether a tokenless user really wants to see a file
625 * @param string $key
626 */
627 private function showFileConfirmationForm( $key ) {
628 $out = $this->getOutput();
629 $lang = $this->getLanguage();
630 $user = $this->getUser();
631 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFilename );
632 $out->addWikiMsg( 'undelete-show-file-confirm',
633 $this->mTargetObj->getText(),
634 $lang->userDate( $file->getTimestamp(), $user ),
635 $lang->userTime( $file->getTimestamp(), $user ) );
636 $out->addHTML(
637 Xml::openElement( 'form', [
638 'method' => 'POST',
639 'action' => $this->getPageTitle()->getLocalURL( [
640 'target' => $this->mTarget,
641 'file' => $key,
642 'token' => $user->getEditToken( $key ),
643 ] ),
644 ]
645 ) .
646 Xml::submitButton( $this->msg( 'undelete-show-file-submit' )->text() ) .
647 '</form>'
648 );
649 }
650
651 /**
652 * Show a deleted file version requested by the visitor.
653 * @param string $key
654 */
655 private function showFile( $key ) {
656 $this->getOutput()->disable();
657
658 # We mustn't allow the output to be CDN cached, otherwise
659 # if an admin previews a deleted image, and it's cached, then
660 # a user without appropriate permissions can toddle off and
661 # nab the image, and CDN will serve it
662 $response = $this->getRequest()->response();
663 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
664 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
665 $response->header( 'Pragma: no-cache' );
666
667 $repo = RepoGroup::singleton()->getLocalRepo();
668 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
669 $repo->streamFile( $path );
670 }
671
672 protected function showHistory() {
673 $this->checkReadOnly();
674
675 $out = $this->getOutput();
676 if ( $this->mAllowed ) {
677 $out->addModules( 'mediawiki.special.undelete' );
678 }
679 $out->wrapWikiMsg(
680 "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n",
681 [ 'undeletepagetitle', wfEscapeWikiText( $this->mTargetObj->getPrefixedText() ) ]
682 );
683
684 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
685 Hooks::run( 'UndeleteForm::showHistory', [ &$archive, $this->mTargetObj ] );
686
687 $out->addHTML( '<div class="mw-undelete-history">' );
688 if ( $this->mAllowed ) {
689 $out->addWikiMsg( 'undeletehistory' );
690 $out->addWikiMsg( 'undeleterevdel' );
691 } else {
692 $out->addWikiMsg( 'undeletehistorynoadmin' );
693 }
694 $out->addHTML( '</div>' );
695
696 # List all stored revisions
697 $revisions = $archive->listRevisions();
698 $files = $archive->listFiles();
699
700 $haveRevisions = $revisions && $revisions->numRows() > 0;
701 $haveFiles = $files && $files->numRows() > 0;
702
703 # Batch existence check on user and talk pages
704 if ( $haveRevisions ) {
705 $batch = new LinkBatch();
706 foreach ( $revisions as $row ) {
707 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
708 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
709 }
710 $batch->execute();
711 $revisions->seek( 0 );
712 }
713 if ( $haveFiles ) {
714 $batch = new LinkBatch();
715 foreach ( $files as $row ) {
716 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
717 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
718 }
719 $batch->execute();
720 $files->seek( 0 );
721 }
722
723 if ( $this->mAllowed ) {
724 $out->enableOOUI();
725
726 $action = $this->getPageTitle()->getLocalURL( [ 'action' => 'submit' ] );
727 # Start the form here
728 $form = new OOUI\FormLayout( [
729 'method' => 'post',
730 'action' => $action,
731 'id' => 'undelete',
732 ] );
733 }
734
735 # Show relevant lines from the deletion log:
736 $deleteLogPage = new LogPage( 'delete' );
737 $out->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) . "\n" );
738 LogEventsList::showLogExtract( $out, 'delete', $this->mTargetObj );
739 # Show relevant lines from the suppression log:
740 $suppressLogPage = new LogPage( 'suppress' );
741 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
742 $out->addHTML( Xml::element( 'h2', null, $suppressLogPage->getName()->text() ) . "\n" );
743 LogEventsList::showLogExtract( $out, 'suppress', $this->mTargetObj );
744 }
745
746 if ( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
747 $fields[] = new OOUI\Layout( [
748 'content' => new OOUI\HtmlSnippet( $this->msg( 'undeleteextrahelp' )->parseAsBlock() )
749 ] );
750
751 $conf = $this->getConfig();
752 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD;
753
754 $fields[] = new OOUI\FieldLayout(
755 new OOUI\TextInputWidget( [
756 'name' => 'wpComment',
757 'inputId' => 'wpComment',
758 'infusable' => true,
759 'value' => $this->mComment,
760 'autofocus' => true,
761 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
762 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
763 // Unicode codepoints (or 255 UTF-8 bytes for old schema).
764 'maxLength' => $oldCommentSchema ? 255 : CommentStore::COMMENT_CHARACTER_LIMIT,
765 ] ),
766 [
767 'label' => $this->msg( 'undeletecomment' )->text(),
768 'align' => 'top',
769 ]
770 );
771
772 $fields[] = new OOUI\FieldLayout(
773 new OOUI\Widget( [
774 'content' => new OOUI\HorizontalLayout( [
775 'items' => [
776 new OOUI\ButtonInputWidget( [
777 'name' => 'restore',
778 'inputId' => 'mw-undelete-submit',
779 'value' => '1',
780 'label' => $this->msg( 'undeletebtn' )->text(),
781 'flags' => [ 'primary', 'progressive' ],
782 'type' => 'submit',
783 ] ),
784 new OOUI\ButtonInputWidget( [
785 'name' => 'invert',
786 'inputId' => 'mw-undelete-invert',
787 'value' => '1',
788 'label' => $this->msg( 'undeleteinvert' )->text()
789 ] ),
790 ]
791 ] )
792 ] )
793 );
794
795 if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
796 $fields[] = new OOUI\FieldLayout(
797 new OOUI\CheckboxInputWidget( [
798 'name' => 'wpUnsuppress',
799 'inputId' => 'mw-undelete-unsuppress',
800 'value' => '1',
801 ] ),
802 [
803 'label' => $this->msg( 'revdelete-unsuppress' )->text(),
804 'align' => 'inline',
805 ]
806 );
807 }
808
809 $fieldset = new OOUI\FieldsetLayout( [
810 'label' => $this->msg( 'undelete-fieldset-title' )->text(),
811 'id' => 'mw-undelete-table',
812 'items' => $fields,
813 ] );
814
815 $form->appendContent(
816 new OOUI\PanelLayout( [
817 'expanded' => false,
818 'padded' => true,
819 'framed' => true,
820 'content' => $fieldset,
821 ] ),
822 new OOUI\HtmlSnippet(
823 Html::hidden( 'target', $this->mTarget ) .
824 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() )
825 )
826 );
827 }
828
829 $history = '';
830 $history .= Xml::element( 'h2', null, $this->msg( 'history' )->text() ) . "\n";
831
832 if ( $haveRevisions ) {
833 # Show the page's stored (deleted) history
834
835 if ( $this->getUser()->isAllowed( 'deleterevision' ) ) {
836 $history .= Html::element(
837 'button',
838 [
839 'name' => 'revdel',
840 'type' => 'submit',
841 'class' => 'deleterevision-log-submit mw-log-deleterevision-button'
842 ],
843 $this->msg( 'showhideselectedversions' )->text()
844 ) . "\n";
845 }
846
847 $history .= '<ul class="mw-undelete-revlist">';
848 $remaining = $revisions->numRows();
849 $earliestLiveTime = $this->mTargetObj->getEarliestRevTime();
850
851 foreach ( $revisions as $row ) {
852 $remaining--;
853 $history .= $this->formatRevisionRow( $row, $earliestLiveTime, $remaining );
854 }
855 $revisions->free();
856 $history .= '</ul>';
857 } else {
858 $out->addWikiMsg( 'nohistory' );
859 }
860
861 if ( $haveFiles ) {
862 $history .= Xml::element( 'h2', null, $this->msg( 'filehist' )->text() ) . "\n";
863 $history .= '<ul class="mw-undelete-revlist">';
864 foreach ( $files as $row ) {
865 $history .= $this->formatFileRow( $row );
866 }
867 $files->free();
868 $history .= '</ul>';
869 }
870
871 if ( $this->mAllowed ) {
872 # Slip in the hidden controls here
873 $misc = Html::hidden( 'target', $this->mTarget );
874 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
875 $history .= $misc;
876
877 $form->appendContent( new OOUI\HtmlSnippet( $history ) );
878 $out->addHTML( $form );
879 } else {
880 $out->addHTML( $history );
881 }
882
883 return true;
884 }
885
886 protected function formatRevisionRow( $row, $earliestLiveTime, $remaining ) {
887 $rev = Revision::newFromArchiveRow( $row,
888 [
889 'title' => $this->mTargetObj
890 ] );
891
892 $revTextSize = '';
893 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
894 // Build checkboxen...
895 if ( $this->mAllowed ) {
896 if ( $this->mInvert ) {
897 if ( in_array( $ts, $this->mTargetTimestamp ) ) {
898 $checkBox = Xml::check( "ts$ts" );
899 } else {
900 $checkBox = Xml::check( "ts$ts", true );
901 }
902 } else {
903 $checkBox = Xml::check( "ts$ts" );
904 }
905 } else {
906 $checkBox = '';
907 }
908
909 // Build page & diff links...
910 $user = $this->getUser();
911 if ( $this->mCanView ) {
912 $titleObj = $this->getPageTitle();
913 # Last link
914 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
915 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
916 $last = $this->msg( 'diff' )->escaped();
917 } elseif ( $remaining > 0 || ( $earliestLiveTime && $ts > $earliestLiveTime ) ) {
918 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
919 $last = $this->getLinkRenderer()->makeKnownLink(
920 $titleObj,
921 $this->msg( 'diff' )->text(),
922 [],
923 [
924 'target' => $this->mTargetObj->getPrefixedText(),
925 'timestamp' => $ts,
926 'diff' => 'prev'
927 ]
928 );
929 } else {
930 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
931 $last = $this->msg( 'diff' )->escaped();
932 }
933 } else {
934 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
935 $last = $this->msg( 'diff' )->escaped();
936 }
937
938 // User links
939 $userLink = Linker::revUserTools( $rev );
940
941 // Minor edit
942 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
943
944 // Revision text size
945 $size = $row->ar_len;
946 if ( !is_null( $size ) ) {
947 $revTextSize = Linker::formatRevisionSize( $size );
948 }
949
950 // Edit summary
951 $comment = Linker::revComment( $rev );
952
953 // Tags
954 $attribs = [];
955 list( $tagSummary, $classes ) = ChangeTags::formatSummaryRow(
956 $row->ts_tags,
957 'deletedhistory',
958 $this->getContext()
959 );
960 if ( $classes ) {
961 $attribs['class'] = implode( ' ', $classes );
962 }
963
964 $revisionRow = $this->msg( 'undelete-revision-row2' )
965 ->rawParams(
966 $checkBox,
967 $last,
968 $pageLink,
969 $userLink,
970 $minor,
971 $revTextSize,
972 $comment,
973 $tagSummary
974 )
975 ->escaped();
976
977 return Xml::tags( 'li', $attribs, $revisionRow ) . "\n";
978 }
979
980 private function formatFileRow( $row ) {
981 $file = ArchivedFile::newFromRow( $row );
982 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
983 $user = $this->getUser();
984
985 $checkBox = '';
986 if ( $this->mCanView && $row->fa_storage_key ) {
987 if ( $this->mAllowed ) {
988 $checkBox = Xml::check( 'fileid' . $row->fa_id );
989 }
990 $key = urlencode( $row->fa_storage_key );
991 $pageLink = $this->getFileLink( $file, $this->getPageTitle(), $ts, $key );
992 } else {
993 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
994 }
995 $userLink = $this->getFileUser( $file );
996 $data = $this->msg( 'widthheight' )->numParams( $row->fa_width, $row->fa_height )->text();
997 $bytes = $this->msg( 'parentheses' )
998 ->plaintextParams( $this->msg( 'nbytes' )->numParams( $row->fa_size )->text() )
999 ->plain();
1000 $data = htmlspecialchars( $data . ' ' . $bytes );
1001 $comment = $this->getFileComment( $file );
1002
1003 // Add show/hide deletion links if available
1004 $canHide = $this->isAllowed( 'deleterevision' );
1005 if ( $canHide || ( $file->getVisibility() && $this->isAllowed( 'deletedhistory' ) ) ) {
1006 if ( !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1007 // Revision was hidden from sysops
1008 $revdlink = Linker::revDeleteLinkDisabled( $canHide );
1009 } else {
1010 $query = [
1011 'type' => 'filearchive',
1012 'target' => $this->mTargetObj->getPrefixedDBkey(),
1013 'ids' => $row->fa_id
1014 ];
1015 $revdlink = Linker::revDeleteLink( $query,
1016 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1017 }
1018 } else {
1019 $revdlink = '';
1020 }
1021
1022 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1023 }
1024
1025 /**
1026 * Fetch revision text link if it's available to all users
1027 *
1028 * @param Revision $rev
1029 * @param Title $titleObj
1030 * @param string $ts Timestamp
1031 * @return string
1032 */
1033 function getPageLink( $rev, $titleObj, $ts ) {
1034 $user = $this->getUser();
1035 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1036
1037 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1038 return '<span class="history-deleted">' . $time . '</span>';
1039 }
1040
1041 $link = $this->getLinkRenderer()->makeKnownLink(
1042 $titleObj,
1043 $time,
1044 [],
1045 [
1046 'target' => $this->mTargetObj->getPrefixedText(),
1047 'timestamp' => $ts
1048 ]
1049 );
1050
1051 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1052 $link = '<span class="history-deleted">' . $link . '</span>';
1053 }
1054
1055 return $link;
1056 }
1057
1058 /**
1059 * Fetch image view link if it's available to all users
1060 *
1061 * @param File|ArchivedFile $file
1062 * @param Title $titleObj
1063 * @param string $ts A timestamp
1064 * @param string $key A storage key
1065 *
1066 * @return string HTML fragment
1067 */
1068 function getFileLink( $file, $titleObj, $ts, $key ) {
1069 $user = $this->getUser();
1070 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1071
1072 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1073 return '<span class="history-deleted">' . htmlspecialchars( $time ) . '</span>';
1074 }
1075
1076 $link = $this->getLinkRenderer()->makeKnownLink(
1077 $titleObj,
1078 $time,
1079 [],
1080 [
1081 'target' => $this->mTargetObj->getPrefixedText(),
1082 'file' => $key,
1083 'token' => $user->getEditToken( $key )
1084 ]
1085 );
1086
1087 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1088 $link = '<span class="history-deleted">' . $link . '</span>';
1089 }
1090
1091 return $link;
1092 }
1093
1094 /**
1095 * Fetch file's user id if it's available to this user
1096 *
1097 * @param File|ArchivedFile $file
1098 * @return string HTML fragment
1099 */
1100 function getFileUser( $file ) {
1101 if ( !$file->userCan( File::DELETED_USER, $this->getUser() ) ) {
1102 return '<span class="history-deleted">' .
1103 $this->msg( 'rev-deleted-user' )->escaped() .
1104 '</span>';
1105 }
1106
1107 $link = Linker::userLink( $file->getRawUser(), $file->getRawUserText() ) .
1108 Linker::userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1109
1110 if ( $file->isDeleted( File::DELETED_USER ) ) {
1111 $link = '<span class="history-deleted">' . $link . '</span>';
1112 }
1113
1114 return $link;
1115 }
1116
1117 /**
1118 * Fetch file upload comment if it's available to this user
1119 *
1120 * @param File|ArchivedFile $file
1121 * @return string HTML fragment
1122 */
1123 function getFileComment( $file ) {
1124 if ( !$file->userCan( File::DELETED_COMMENT, $this->getUser() ) ) {
1125 return '<span class="history-deleted"><span class="comment">' .
1126 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></span>';
1127 }
1128
1129 $link = Linker::commentBlock( $file->getRawDescription() );
1130
1131 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1132 $link = '<span class="history-deleted">' . $link . '</span>';
1133 }
1134
1135 return $link;
1136 }
1137
1138 function undelete() {
1139 if ( $this->getConfig()->get( 'UploadMaintenance' )
1140 && $this->mTargetObj->getNamespace() == NS_FILE
1141 ) {
1142 throw new ErrorPageError( 'undelete-error', 'filedelete-maintenance' );
1143 }
1144
1145 $this->checkReadOnly();
1146
1147 $out = $this->getOutput();
1148 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1149 Hooks::run( 'UndeleteForm::undelete', [ &$archive, $this->mTargetObj ] );
1150 $ok = $archive->undelete(
1151 $this->mTargetTimestamp,
1152 $this->mComment,
1153 $this->mFileVersions,
1154 $this->mUnsuppress,
1155 $this->getUser()
1156 );
1157
1158 if ( is_array( $ok ) ) {
1159 if ( $ok[1] ) { // Undeleted file count
1160 Hooks::run( 'FileUndeleteComplete', [
1161 $this->mTargetObj, $this->mFileVersions,
1162 $this->getUser(), $this->mComment ] );
1163 }
1164
1165 $link = $this->getLinkRenderer()->makeKnownLink( $this->mTargetObj );
1166 $out->addHTML( $this->msg( 'undeletedpage' )->rawParams( $link )->parse() );
1167 } else {
1168 $out->setPageTitle( $this->msg( 'undelete-error' ) );
1169 }
1170
1171 // Show revision undeletion warnings and errors
1172 $status = $archive->getRevisionStatus();
1173 if ( $status && !$status->isGood() ) {
1174 $out->addWikiText( '<div class="error" id="mw-error-cannotundelete">' .
1175 $status->getWikiText(
1176 'cannotundelete',
1177 'cannotundelete'
1178 ) . '</div>'
1179 );
1180 }
1181
1182 // Show file undeletion warnings and errors
1183 $status = $archive->getFileStatus();
1184 if ( $status && !$status->isGood() ) {
1185 $out->addWikiText( '<div class="error">' .
1186 $status->getWikiText(
1187 'undelete-error-short',
1188 'undelete-error-long'
1189 ) . '</div>'
1190 );
1191 }
1192 }
1193
1194 /**
1195 * Return an array of subpages beginning with $search that this special page will accept.
1196 *
1197 * @param string $search Prefix to search for
1198 * @param int $limit Maximum number of results to return (usually 10)
1199 * @param int $offset Number of results to skip (usually 0)
1200 * @return string[] Matching subpages
1201 */
1202 public function prefixSearchSubpages( $search, $limit, $offset ) {
1203 return $this->prefixSearchString( $search, $limit, $offset );
1204 }
1205
1206 protected function getGroupName() {
1207 return 'pagetools';
1208 }
1209 }